const express = require('express');
const router = express.Router();
const { authenticateToken, requireRole } = require('../middleware/auth');
const reportController = require('../controllers/reportController');
const financialReportController = require('../controllers/financialReportController');
const salesReportController = require('../controllers/salesReportController');
const productReportController = require('../controllers/productReportController');
const customerReportController = require('../controllers/customerReportController');

// 权限验证中间件
const requireReportPermission = (reportKey) => {
  return async (req, res, next) => {
    try {
      const userId = req.user.id;
      const userRole = req.user.role;
      
      // 检查用户是否有该报表的访问权限
      const hasPermission = await reportController.checkReportPermission(userId, userRole, reportKey);
      
      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '没有访问该报表的权限'
        });
      }
      
      next();
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '权限验证失败',
        error: error.message
      });
    }
  };
};

// 通用报表路由

// 获取报表列表
router.get('/', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const userRole = req.user.role;
    const result = await reportController.getReportList(userId, userRole);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取报表列表失败',
      error: error.message
    });
  }
});

// 获取报表配置
router.get('/config/:reportKey', authenticateToken, requireReportPermission(':reportKey'), async (req, res) => {
  try {
    const { reportKey } = req.params;
    const result = await reportController.getReportConfig(reportKey);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取报表配置失败',
      error: error.message
    });
  }
});

// 导出报表
router.post('/export/:reportKey', authenticateToken, requireReportPermission(':reportKey'), async (req, res) => {
  try {
    const { reportKey } = req.params;
    const { format = 'xlsx', filters = {} } = req.body;
    const userId = req.user.id;
    
    const result = await reportController.exportReport(reportKey, format, filters, userId);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '导出报表失败',
      error: error.message
    });
  }
});

// 获取导出状态
router.get('/export/status/:exportId', authenticateToken, async (req, res) => {
  try {
    const { exportId } = req.params;
    const result = await reportController.getExportStatus(exportId);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取导出状态失败',
      error: error.message
    });
  }
});

// 下载导出文件
router.get('/export/download/:exportId', authenticateToken, async (req, res) => {
  try {
    const { exportId } = req.params;
    await reportController.downloadExportFile(exportId, res);
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '下载文件失败',
      error: error.message
    });
  }
});

// ==================== 财务类报表 ====================

// 1. 现金申报报表 (Cash Declaration Report)
router.post('/financial/cash-declaration', 
  authenticateToken, 
  requireReportPermission('cash_declaration'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await financialReportController.getCashDeclarationReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成现金申报报表失败',
        error: error.message
      });
    }
  }
);

// 2. 每日收款汇总 (Daily Collection)
router.post('/financial/daily-collection', 
  authenticateToken, 
  requireReportPermission('daily_collection'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await financialReportController.getDailyCollectionReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成每日收款汇总失败',
        error: error.message
      });
    }
  }
);

// 3. 支付报表 (Payment Report)
router.post('/financial/payment-report', 
  authenticateToken, 
  requireReportPermission('payment_report'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await financialReportController.getPaymentReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成支付报表失败',
        error: error.message
      });
    }
  }
);

// 4. 利润分析报表 (Profit Analysis Report)
router.post('/financial/profit-analysis', 
  authenticateToken, 
  requireReportPermission('profit_analysis'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await financialReportController.getProfitAnalysisReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成利润分析报表失败',
        error: error.message
      });
    }
  }
);

// ==================== 销售类报表 ====================

// 5. 每日销售摘要 (Daily Sales Summary)
router.post('/sales/daily-summary', 
  authenticateToken, 
  requireReportPermission('daily_sales_summary'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await salesReportController.getDailySalesSummaryReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成每日销售摘要失败',
        error: error.message
      });
    }
  }
);

// 6. 小时经营分析 (Hourly Analysis Report)
router.post('/sales/hourly-analysis', 
  authenticateToken, 
  requireReportPermission('hourly_analysis'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await salesReportController.getHourlyAnalysisReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成小时经营分析失败',
        error: error.message
      });
    }
  }
);

// 7. 小时总览 (Hourly Report)
router.post('/sales/hourly-overview', 
  authenticateToken, 
  requireReportPermission('hourly_overview'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await salesReportController.getHourlyOverviewReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成小时总览失败',
        error: error.message
      });
    }
  }
);

// 8. 销售与客数 (Sales And Count)
router.post('/sales/sales-and-count', 
  authenticateToken, 
  requireReportPermission('sales_and_count'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await salesReportController.getSalesAndCountReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成销售与客数报表失败',
        error: error.message
      });
    }
  }
);

// ==================== 商品类报表 ====================

// 9. 商品销售报表 (Product Sales Report)
router.post('/product/sales-report', 
  authenticateToken, 
  requireReportPermission('product_sales'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await productReportController.getProductSalesReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成商品销售报表失败',
        error: error.message
      });
    }
  }
);

// 10. 商品分析报表 (Product Analysis Report)
router.post('/product/analysis-report', 
  authenticateToken, 
  requireReportPermission('product_analysis'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await productReportController.getProductAnalysisReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成商品分析报表失败',
        error: error.message
      });
    }
  }
);

// 11. 商品退货/退款报表 (Product Return Report)
router.post('/product/return-report', 
  authenticateToken, 
  requireReportPermission('product_return'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await productReportController.getProductReturnReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成商品退货报表失败',
        error: error.message
      });
    }
  }
);

// 12. 配料/小料报表 (Condiments Report)
router.post('/product/condiments-report', 
  authenticateToken, 
  requireReportPermission('condiments_report'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await productReportController.getCondimentsReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成配料报表失败',
        error: error.message
      });
    }
  }
);

// 13. 折扣报表 (Discount Report)
router.post('/product/discount-report', 
  authenticateToken, 
  requireReportPermission('discount_report'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await productReportController.getDiscountReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成折扣报表失败',
        error: error.message
      });
    }
  }
);

// ==================== 顾客与服务类报表 ====================

// 14. 顾客评分报表 (Rating Report)
router.post('/customer/rating-report', 
  authenticateToken, 
  requireReportPermission('rating_report'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await customerReportController.getRatingReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成顾客评分报表失败',
        error: error.message
      });
    }
  }
);

// 15. 小票流水/凭证日记账 (Receipt Journal)
router.post('/customer/receipt-journal', 
  authenticateToken, 
  requireReportPermission('receipt_journal'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await customerReportController.getReceiptJournalReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成小票流水报表失败',
        error: error.message
      });
    }
  }
);

// 16. 小时商品明细 (Hourly Item Report)
router.post('/customer/hourly-item-report', 
  authenticateToken, 
  requireReportPermission('hourly_item_report'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await customerReportController.getHourlyItemReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成小时商品明细失败',
        error: error.message
      });
    }
  }
);

// 17. 支付 × 商品报表 (Payment Product Report)
router.post('/customer/payment-product-report', 
  authenticateToken, 
  requireReportPermission('payment_product_report'), 
  async (req, res) => {
    try {
      const filters = req.body;
      const result = await customerReportController.getPaymentProductReport(filters);
      
      res.json({
        success: true,
        data: result
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '生成支付商品报表失败',
        error: error.message
      });
    }
  }
);

// ==================== 报表管理路由 ====================

// 报表权限管理
router.get('/permissions', authenticateToken, requireRole(['admin', 'manager']), async (req, res) => {
  try {
    const result = await reportController.getReportPermissions();
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取报表权限失败',
      error: error.message
    });
  }
});

// 更新报表权限
router.put('/permissions', authenticateToken, requireRole(['admin']), async (req, res) => {
  try {
    const { role, reportKey, permissions } = req.body;
    const result = await reportController.updateReportPermissions(role, reportKey, permissions);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新报表权限失败',
      error: error.message
    });
  }
});

// 报表订阅管理
router.get('/subscriptions', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const result = await reportController.getReportSubscriptions(userId);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取报表订阅失败',
      error: error.message
    });
  }
});

// 创建报表订阅
router.post('/subscriptions', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const subscriptionData = { ...req.body, user_id: userId };
    const result = await reportController.createReportSubscription(subscriptionData);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建报表订阅失败',
      error: error.message
    });
  }
});

// 更新报表订阅
router.put('/subscriptions/:subscriptionId', authenticateToken, async (req, res) => {
  try {
    const { subscriptionId } = req.params;
    const userId = req.user.id;
    const updateData = req.body;
    
    const result = await reportController.updateReportSubscription(subscriptionId, updateData, userId);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新报表订阅失败',
      error: error.message
    });
  }
});

// 删除报表订阅
router.delete('/subscriptions/:subscriptionId', authenticateToken, async (req, res) => {
  try {
    const { subscriptionId } = req.params;
    const userId = req.user.id;
    
    const result = await reportController.deleteReportSubscription(subscriptionId, userId);
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除报表订阅失败',
      error: error.message
    });
  }
});

module.exports = router;